package main

import (
	"fmt"
	"github.com/spf13/cobra"
	"os"
	"os/exec"
)

func main() {
	rootCmd := &cobra.Command{
		Use:   "gotham",
		Short: "Gotham command-line tool",
	}

	genPbCmd := &cobra.Command{
		Use:   "genpb",
		Short: "Generate protobuf files",
		Run: func(cmd *cobra.Command, args []string) {
			err := updateProtoRepositories()
			if err != nil {
				fmt.Println(err)
				os.Exit(1)
			}
			fmt.Println("Proto update and generation completed.")
		},
	}
	rootCmd.AddCommand(genPbCmd)

	err := rootCmd.Execute()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

// Updates proto repositories and generates proto files
func updateProtoRepositories() error {
	protoDir := "proto"

	entries, err := os.ReadDir(protoDir)
	if err != nil {
		return fmt.Errorf("Failed to read proto directory: %s", err.Error())
	}
	err = os.Chdir("proto")
	if err != nil {
		return fmt.Errorf("Failed to switch back to the original directory: %s", err.Error())
	}

	for _, entry := range entries {
		if entry.IsDir() {
			// Switch to the proto repository directory
			//join := filepath.Join(protoDir, )
			err := os.Chdir(entry.Name())
			if err != nil {
				return fmt.Errorf("Failed to switch to proto repository: %s", err.Error())
			}

			// Run git pull
			err = gitPull()
			if err != nil {
				return err
			}

			// Switch back to the original directory
			err = os.Chdir("..")
			if err != nil {
				return fmt.Errorf("Failed to switch back to the original directory: %s", err.Error())
			}
		}
	}
	// Run proto generation command
	err = generateProto()
	if err != nil {
		return err
	}

	return nil
}

// Executes "git pull" command
func gitPull() error {
	cmd := exec.Command("git", "pull")
	err := cmd.Run()
	if err != nil {
		return fmt.Errorf("Failed to run 'git pull' command: %s", err.Error())
	}

	return nil
}

// Executes proto generation command
func generateProto() error {
	// Replace the command below with your actual proto generation command
	cmd := exec.Command("kratos", "proto", "client", ".")
	output, err := cmd.CombinedOutput()
	fmt.Println(string(output))
	if err != nil {
		return fmt.Errorf("Failed to generate proto files: %s", err.Error())
	}
	return nil
}
